package com.allianz.webapps.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.allianz.webapps.https.interfaces.appInitProduct.AppInitProduct;
import com.allianz.webapps.https.interfaces.util.HttpsUtil;
import com.allianz.webapps.orderspojo.App;
import com.allianz.webapps.orderspojo.AppBase;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("main")
public class AppInitProductController {
 
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private AppInitProduct appInitProduct;
	@RequestMapping("appinitproduct")
	@ResponseBody
	public App appInitProduct(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request,
			HttpServletResponse response) throws JsonProcessingException,
			Exception {
		/**
		 * 前端传参格式{'appId':'350957','orderId':'324541','sign':'20C250AE423F3C194159C72F9657D8BA'}
		 */
		Map<String, String> bodymap = new HashMap<String, String>();
		AppBase appBase=objectMapper.readValue(jsonParam, AppBase.class);
		String body1 = HttpsUtil.httpsPost(appInitProduct.requestAppInitProduct(appBase));
		JSONObject json = new JSONObject(body1);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        
		String body = null;
		if (json.get("Body").equals(null)) {
			if(!"S".equals(json.getString("Status")))
				throw new Exception(json.getString("ErrMsg"));
			else
				return null;
		}else{
			body = json.getString("Body");
			App app = objectMapper.readValue(body, App.class);
			return app;
		}
	}
}